/**
 * 系统名称: 企业财资
 * 模块名称: repair-boot
 * 类 名 称: GetSerialNum.java
 * 软件版权: 恒生电子股份有限公司
 * 修改记录:
 * 修改人员:
 * 修改说明:
 * ============ ============================================
 * zhanghong 创建
 * ============ ============================================
 */
package com.mt.repair.utils;

import com.mt.common.core.security.RedisUtil;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 *
 * @author zhanghong
 * @date 2023-02-19 16:58
 */
@Component
public class GetSerialNum {
    @Autowired
    private  RedisUtil redisUtil;
    @Autowired
    private  Redisson redisson;

    public static String repairOrderLock="repairLock";
    public static String repairNum="repairNum";
    public static String deviceLock="deviceLock";
    public static String deviceNum="deviceNum";

    public  String getSerialNum(String lock,String numKey,int dayLength){
        RLock serialNumLock = redisson.getLock(lock);
        serialNumLock.lock();
        try {
            boolean toDaySerialNum = redisUtil.hasKey(numKey);
            if(!toDaySerialNum){
                redisUtil.set(numKey,0);
            }
            String now = String.valueOf(redisUtil.incr(numKey, 1));
            String toDay=new SimpleDateFormat("yyyyMMdd").format(new Date());
            StringBuffer sb=new StringBuffer(toDay);
            for (int i = now.length(); i < dayLength; i++) {
                sb.append("0");
            }
            sb.append(now);

            serialNumLock.unlock();
            return sb.toString();

        }catch (Exception e){
            e.printStackTrace();
            serialNumLock.unlock();
            return null;
        }
    }
}
